package cn.luoshaocheng.pet.service.impl;

import cn.luoshaocheng.basic.service.impl.BaseServiceImpl;
import cn.luoshaocheng.org.domain.Department;
import cn.luoshaocheng.pet.domain.PetDetail;
import cn.luoshaocheng.pet.domain.PetType;
import cn.luoshaocheng.pet.mapper.PetTypeMapper;
import cn.luoshaocheng.pet.service.IPetDetailService;
import cn.luoshaocheng.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTree() {
        //获取全部部门信息
        List<PetType> list = petTypeMapper.loadAll();
        //准备一个map集合，用来装所有的部门
        HashMap<Long, PetType> map = new HashMap<>();
        //遍历所有的部门信息
        for (PetType petType : list) {
            //将部门信息装入map集合中
            map.put(petType.getId(), petType);
        }

        List<PetType> typeTree= new ArrayList<>();
        for (PetType petType : list) {
            if (petType.getPid() == null) {//顶级部门
                typeTree.add(petType);
            } else {
                //获取不是顶级部门的id
                Long pid=petType.getPid();
                //通过id在map里面去获取响应的部门信息
                PetType parentType = map.get(pid);
                //将自己添加到上级部门里面
                parentType.getChildren().add(petType);
            }
        }
        return typeTree;

    }
}

